// Copyright (c) 2012-2013, yuno. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of contributors
//    may be used to endorse or promote products derived from this software
//    without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
package sugarmintcandy.widgetwindow;

import java.util.HashSet;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.RemoteViews;

public class ControlWidget extends AppWidgetProvider {
    @Override
    public void onReceive(Context context, Intent intent) {
	if (ApiHelper.SDK_INT == 3) {
	    // workaround for Android 1.5
	    // http://groups.google.com/group/android-developers/msg/e405ca19df2170e2
	    String action = intent.getAction();
	    if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
		int appWidgetId = intent.getIntExtra(
			AppWidgetManager.EXTRA_APPWIDGET_ID,
			AppWidgetManager.INVALID_APPWIDGET_ID);
		if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
		    onDeleted(context, new int[] { appWidgetId });
		}
		return;
	    }
	}
	super.onReceive(context, intent);
    }

    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
	super.onDeleted(context, appWidgetIds);
	MainApplication app = (MainApplication) context.getApplicationContext();
	MainDatabase db = app.getDatabase();
	for (int id : appWidgetIds) {
	    db.deleteControlWidget(id);
	}
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
	    int[] appWidgetIds) {
	super.onUpdate(context, appWidgetManager, appWidgetIds);
	if (appWidgetIds != null) {
	    HashSet<Integer> validIds = new HashSet<Integer>();
	    for (int id : appWidgetManager.getAppWidgetIds(new ComponentName(
		    context, ControlWidget.class))) {
		validIds.add(id);
	    }
	    for (int id : appWidgetIds) {
		if (validIds.contains(id)) {
		    doUpdate(context, id);
		}
	    }
	}
    }

    public static void doUpdate(Context context) {
	AppWidgetManager manager = AppWidgetManager.getInstance(context);
	int[] appWidgetIds = manager.getAppWidgetIds(new ComponentName(context,
		ControlWidget.class));
	if (appWidgetIds != null) {
	    for (int id : appWidgetIds) {
		manager.updateAppWidget(id, createRemoteViews(context, id));
	    }
	}
    }

    public static void doUpdate(Context context, int appWidgetId) {
	AppWidgetManager manager = AppWidgetManager.getInstance(context);
	manager.updateAppWidget(appWidgetId,
		createRemoteViews(context, appWidgetId));
    }

    private static final int[] buttonIds = { 0, R.id.workspace_button_1,
	    R.id.workspace_button_2, R.id.workspace_button_3,
	    R.id.workspace_button_4, R.id.workspace_button_5,
	    R.id.workspace_button_6, R.id.workspace_button_7,
	    R.id.workspace_button_8, R.id.workspace_button_9,
	    R.id.workspace_button_10 };

    private static final int[] selectedButtonIds = { 0,
	    R.id.workspace_button_1_selected, R.id.workspace_button_2_selected,
	    R.id.workspace_button_3_selected, R.id.workspace_button_4_selected,
	    R.id.workspace_button_5_selected, R.id.workspace_button_6_selected,
	    R.id.workspace_button_7_selected, R.id.workspace_button_8_selected,
	    R.id.workspace_button_9_selected, R.id.workspace_button_10_selected };

    private static RemoteViews createRemoteViews(Context context,
	    int appWidgetId) {
	MainApplication app = (MainApplication) context.getApplicationContext();
	MainDatabase db = app.getDatabase();
	int buttons = db.getControlWidgetButtons(appWidgetId);
	SharedPreferences prefs = PreferenceManager
		.getDefaultSharedPreferences(context);
	int currentWorkspace = prefs
		.getInt(PreferenceKeys.CURRENT_WORKSPACE, 0);
	RemoteViews views = new RemoteViews(context.getPackageName(),
		R.layout.control_widget);
	if ((buttons & 1) != 0) {
	    views.setOnClickPendingIntent(R.id.open_window,
		    MainBroadcastReceiver.getOpenWindowPendingIntent(context));
	} else {
	    views.setViewVisibility(R.id.open_window, View.GONE);
	}
	for (int i = 1; i <= 10; i++) {
	    PendingIntent intent = MainBroadcastReceiver
		    .getSwitchWorkspacePendingIntent(context, i);
	    int id = buttonIds[i];
	    int selectedId = selectedButtonIds[i];
	    if ((buttons & (1 << i)) == 0) {
		views.setViewVisibility(id, View.GONE);
		views.setViewVisibility(selectedId, View.GONE);
	    } else if (currentWorkspace == i) {
		views.setViewVisibility(id, View.GONE);
		views.setViewVisibility(selectedId, View.VISIBLE);
		views.setOnClickPendingIntent(selectedId, intent);
	    } else {
		views.setViewVisibility(id, View.VISIBLE);
		views.setViewVisibility(selectedId, View.GONE);
		views.setOnClickPendingIntent(id, intent);
	    }
	}
	return views;
    }
}
